package lib.servlet;

import lib.Dao.CourseDAO;
import lib.Dao.UserDao;
import lib.Dao.Dbutil;
import lib.Model.UserAdd;
import lib.util.PostPaiedMessage;
import lib.wxpay.sdk.WXPayUtil;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.Map;
import lib.Dao.CourseUserDAO;

@WebServlet(urlPatterns = "/paied", name = "paied")
public class UseraddServlet extends HttpServlet {
    Dbutil dbutil = new Dbutil();
    UserDao userDao=new UserDao();
    CourseUserDAO courseUserDAO=new CourseUserDAO();
    CourseDAO courseDAO=new CourseDAO();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        InputStream is = null;
        try {
            is = req.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = IOUtils.toString(is, "utf-8");
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map

            if(notifyMap.get("return_code").equals("SUCCESS")){
                if(notifyMap.get("result_code").equals("SUCCESS")){
                    String cid = notifyMap.get("attach");
                    String openid = notifyMap.get("openid");  //如果有需要可以获取
                   /*以下是自己的业务处理-
                     *
                     */
                    userDao.useradd(openid,cid);
                    courseUserDAO.CourseUseradd(cid,openid);
                    courseDAO.SetCcount(userDao.getUserSe(openid),cid);
                    PostPaiedMessage postPaiedMessage=new PostPaiedMessage();
                    postPaiedMessage.posttoopenid(openid,cid);

                }
            }

            //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
            resp.getWriter().write("<xml>" +
                    "<return_code><![CDATA[SUCCESS]]></return_code>" +
                    "<return_msg><![CDATA[OK]]></return_msg>" +
                    "</xml>");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }
}